package com.mmall.concurrency.controller;

import com.google.common.util.concurrent.RateLimiter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:LiuWei
 * @Description:
 * @Date: Created in 14:31 2019/7/3
 * @Modified By:
 */
@RestController
public class TokenBucketController {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private static final RateLimiter rateLimiter = RateLimiter.create(3.0);

    private static AtomicInteger userNum = new AtomicInteger(0);

    //1、10个请求，每个请求需要的时间是10s以内
    //2、service中一个方法是能同时处理2个请求，每个请求处理的时间是3s，也就是9s能够6个请求
    //3、最后1s则会导致2个请求超时，同时20个请求未进行service方法处理也超时。总之6个请求正常，4个请求超时，10s之内返回，不影响后面的请求
    @GetMapping("limitTokenBucket")
    public String limitTokenBucketDemo() {
        int num = userNum.get();
        userNum.incrementAndGet();
        if (rateLimiter.tryAcquire()) { //  一次拿1个
            System.out.println("request  time user-"+num+"  "+sdf.format(new Date()));
            try {

                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Response time user-"+num+"  "+sdf.format(new Date()));
            return "success";
        } else {
            System.out.println("limit");
            return "limit";
        }


    }


}

